package com.scanner.hardware;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.scanner.barcodeservice.SerialPortService;
import com.scanner.bean.Constans;
import com.scanner.bean.ScanSetting;
import com.scanner.database.DatabaseHelper;
import com.scanner.ui.PublicTipsDialog;
import com.scanner.util.BaseUtils;
import com.scanner.util.CheckAppUpdateUtil;
import com.scanner.util.DataUtil;
import com.scanner.util.ExcelOperator;
import com.scanner.util.FileUtil;
import com.scanner.util.HardwareInfoUtill;
import com.scanner.util.LogUtil;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class StartActivity extends AppCompatActivity implements OnClickListener,EasyPermissions.PermissionCallbacks{
	private static final String TAG = "StartActivity"; 

	private TextView show;
	private Button startButton,startTime,startSave;
	private TextView clearButton;
	private String path_result = "/sdcard/ScanResult";
    private SQLiteDatabase writableDatabase;
    private DatabaseHelper databaseHelper;
	private ScrollView svShow;
	private Toolbar toolbar;
	private CheckAppUpdateUtil appUpdateUtil;
    private Intent screenMonitorServiceIntent;
    private int deviceType;//设备的类型

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ScanSetting settingFormShare = BaseUtils.getSettingFormShare();
		String screenDirection = settingFormShare.getScreenDirection();
		if("Vertical".equalsIgnoreCase(screenDirection)){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制为竖屏
		}else if("Horizontal".equalsIgnoreCase(screenDirection)){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
		}
		setContentView(R.layout.activity_start);
		Log.d(TAG, "onCreate="+screenDirection);
		initViews();
        databaseHelper = new DatabaseHelper(StartActivity.this, getFilesDir()+"/barcode.db3", null, 1);
        writableDatabase = databaseHelper.getWritableDatabase();
		IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SerialPortService.BARCODEPORT_RECEIVEDDATA_ACTION);
        registerReceiver(receiver, intentFilter);

        methodRequiresPermission();

        deviceType = settingFormShare.getScanModule();
		if(deviceType == Constans.DTMoTOSE2707 || deviceType == Constans.DTMoToSE655){//加载条码数据
			MyApplication.getApplication().LoadAllMotoSetting();
		}

		String deviceNum = HardwareInfoUtill.getInstance(this).getDeviceNum();
		LogUtil.d("设备信息好==="+deviceNum);

	}



	
	@SuppressLint("ClickableViewAccessibility")
	private void initViews(){
		show = (TextView)findViewById(R.id.show);
		startButton = (Button)findViewById(R.id.button_start);
		startButton.setOnClickListener(this);
		startTime  = (Button)findViewById(R.id.button_time);
		startTime.setOnClickListener(this);
		startSave  = (Button)findViewById(R.id.button_save);
		startSave.setOnClickListener(this);
		svShow = findViewById(R.id.sv_show);
		clearButton = (TextView)findViewById(R.id.button_clear);
		clearButton.setOnClickListener(this);
		toolbar = findViewById(R.id.main_toolbar);
		toolbar.inflateMenu(R.menu.setting);
		toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				int id = item.getItemId();
				if (id == R.id.settings) {
					Intent mIntent = new Intent(StartActivity.this,JsbSettingActivity.class);
					startActivity(mIntent);
					return true;
				}else if(id == R.id.symbologies){
                    ScanSetting settingFormShare = BaseUtils.getSettingFormShare();
                    deviceType = settingFormShare.getScanModule();
                    if(deviceType>4 || deviceType == 0){
                        return true;
                    }
					Intent mIntent = null;
					if(deviceType == Constans.DTHONEYWELL){//二维，啊
						mIntent = new Intent(StartActivity.this,SymbologiesQR.class);
					}else if(deviceType == Constans.DTHONEYWELLONE){//一维码
						mIntent = new Intent(StartActivity.this,SymbologiesSig.class);
					}else if(deviceType == Constans.DTMoToSE655){//摩托一维码
						mIntent = new Intent(StartActivity.this,MotoSigCodeActivity.class);
					}else if(deviceType == Constans.DTMoTOSE2707){//摩托二维
						mIntent = new Intent(StartActivity.this,MotoQRcodeActivity.class);
					}

					StartActivity.this.startActivity(mIntent);
					return true;
				}else if(id == R.id.about){
					Intent mIntent = new Intent(StartActivity.this,AboutActivity.class);
					StartActivity.this.startActivity(mIntent);
					return true;
				}else if(id == R.id.export){

					ExcelOperator.createFolder(path_result);//写进Excel表格
					ExcelOperator.write(StartActivity.this,dataExcelPath());
					Toast.makeText(StartActivity.this, "The result had export to " + path_result, Toast.LENGTH_LONG).show();
					databaseHelper.delete(writableDatabase);
					return true;
				}else if(id == R.id.jump_setting){
					Intent intent = new Intent(StartActivity.this,ChooseScannerActivity.class);
					intent.putExtra("jump_type",1);
					startActivity(intent);
				}
				return true;
			}
		});

		clearButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_UP){
					PublicTipsDialog dialog = PublicTipsDialog.getInstance(getString(R.string.tips_ki));
					dialog.addDialogOnClick(new PublicTipsDialog.OnDialogBtnClickListener() {
						@Override
						public void sureOnClick() {
							databaseHelper.delete(writableDatabase);
							show.setText("");
						}

						@Override
						public void cancelOnClick() {
							show.setText("");
						}
					});

					dialog.show(getSupportFragmentManager(),"zx");
				}

				return false;
			}
		});

	}
	
	  @Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
		if(screenMonitorServiceIntent != null){
		    stopService(screenMonitorServiceIntent);
        }
	}

	/**
     * 广播接收器
     * */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            // TODO Auto-generated method stub
            String action = intent.getAction();
            if(action!=null){
            	LogUtil.d("收到广播action"+action);
				if (action.equals(SerialPortService.BARCODEPORT_RECEIVEDDATA_ACTION)) {
					String stringExtra = intent.getStringExtra(SerialPortService.BARCODEPROT_RECEIVEDATA_TYPE);
					if (SerialPortService.BARCODEPROT_RECEIVEDATA_TYPE.equals(stringExtra)) {//是硬解
						String data = intent.getStringExtra(SerialPortService.BARCODEPORT_RECEIVEDDATA_EXTRA_DATA) + "\n";
						show.append(data);
						LogUtil.i("广播接收到数据=" + data);
						if (svShow != null) {
							svShow.post(new Runnable() {
								public void run() {
									svShow.fullScroll(View.FOCUS_DOWN);
								}
							});
						}
					}

				}
            }
        }
    };


 
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button_start:
			
		   // Intent mIntent = new Intent();
		  //  ComponentName componentName = new ComponentName("com.android.barcodescanner","com.android.barcodeservice.SerialPortService");
		   // mIntent.setComponent(componentName);
		    
			Intent  mIntent = new Intent(this,SerialPortService.class);
			StartActivity.this.startService(mIntent);
		    
		    //startService(mIntent);
		    startButton.setEnabled(false);
			break;
			
		case R.id.button_clear:

			break;
			
		case R.id.button_time:
			Intent intent = new Intent(SerialPortService.BARCODEPORT_WRITEDATA_ACTION);
			intent.putExtra(SerialPortService.BARCODEPORT_WRITEDATA_EXTRA_DATA, "Rev?.");
			//intent.putExtra(SerialPortService.BARCODEPORT_WRITEDATA_EXTRA_DATA, "pwrmod?.");
			this.sendBroadcast(intent);
			break;

		default:
			break;
		}
		
	}


	@Override
	public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
		LogUtil.i("权限统一");
        new FileUtil(this).init();
		Intent screenMonitorServiceIntent=new Intent(this,SerialPortService.class);
		if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N_MR1){
			startForegroundService(screenMonitorServiceIntent);
		}else {
			startService(screenMonitorServiceIntent);
		}

	}

	private String dataExcelPath(){
	    return FileUtil.SDPATH +"scan_result" + DataUtil.getCurrentDateString() + ".xls";
    }

	@Override
	public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
		LogUtil.i("权限没有");
		if (requestCode == REQUEST_READPHONE_CODE) {
			if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
				new AppSettingsDialog.Builder(this)
						.setRationale(R.string.file_peress)
						.setTitle(R.string.file_request)
						.build().show();
			}

		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
	}
	/**
	 * 申请权限
	 */
	private static final int REQUEST_READPHONE_CODE = 1010;

	@AfterPermissionGranted(REQUEST_READPHONE_CODE)
	public void methodRequiresPermission() {
		String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
		if (EasyPermissions.hasPermissions(StartActivity.this, perms)) {
			//开机时不自动启动该app，进入该app时启动
            screenMonitorServiceIntent = new Intent(this,SerialPortService.class);
			if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N_MR1){
				startForegroundService(screenMonitorServiceIntent);
			}else {
				startService(screenMonitorServiceIntent);
			}

			Toast.makeText(this, getResources().getString(R.string.start_serialport_service),
					Toast.LENGTH_SHORT).show();
			new FileUtil(this).init();
			appUpdateUtil = CheckAppUpdateUtil.getInstance(StartActivity.this, false);
			appUpdateUtil.checkLastVersionFromService();
			appUpdateUtil.appDownSuccessListener(new CheckAppUpdateUtil.OnAppDownSuccessListener() {
				@Override
				public void success(String apkPath) {
					installProcess(apkPath);
				}
			});
		} else {
			EasyPermissions.requestPermissions(this, getString(R.string.app_name),
					REQUEST_READPHONE_CODE, perms);
		}
	}

	private String apkPath;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 10) {
			if (Build.VERSION.SDK_INT >= 23) {
				if (!Settings.canDrawOverlays(this)) {
					// SYSTEM_ALERT_WINDOW permission not granted...
					Toast.makeText(this,"not granted",Toast.LENGTH_SHORT).show();
				}
			}
		}else if(requestCode == GET_UNKNOWN_APP_SOURCES){
			installProcess(apkPath);
		}
	}

	//安装应用的流程
	public void installProcess(String apkFileString) {
		apkPath = apkFileString;
		boolean haveInstallPermission;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			//先获取是否有安装未知来源应用的权限
			haveInstallPermission = getPackageManager().canRequestPackageInstalls();
			if (!haveInstallPermission) {//没有权限
				startInstallPermissionSettingActivity();
				return;
			}
		}
		appUpdateUtil.install(apkFileString);
	}

	public static final int GET_UNKNOWN_APP_SOURCES = 12120;

	@RequiresApi(api = Build.VERSION_CODES.O)
	private void startInstallPermissionSettingActivity() {
		Uri packageURI = Uri.parse("package:" + getPackageName());
		//注意这个是8.0新API
		Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
		startActivityForResult(intent,GET_UNKNOWN_APP_SOURCES);
	}


	private long exitTime = 0;


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 1500) {
				Toast.makeText(this,getString(R.string.exit_app_tips),Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				//退出前应该先保存下资料
				//   saveIntoDB(AppApplication.consumer);
				finish();
//				System.exit(0);
			}
			return true;
		}else if(keyCode == KeyEvent.KEYCODE_F8){
			/*Intent intent=new Intent(SerialPortService.ACTION_KEYEVENT_KEYCODE_SCAN_L_DOWN);

			sendBroadcast(intent);*/
		}
		return super.onKeyDown(keyCode, event);
	}


}
